/**
 * 左侧公共区划单位树
 */
//全局变量
var AD_ID = '';
var AD_CODE = '';
var AD_NAME = '';
var AG_ID = '';
var AG_CODE = '';
var AG_NAME = '';
var SHOW_NUM = getQueryParam("show_num");
var VIEW_NAME = getQueryParam("view_name");
var leftTreeConfig = {
    areaConfig: {
        params: {
            //CHILD: 0//区划树参数，1显示下级，其它显示原值，默认显示全部
        }
    },
    items_tree: function () {
        return [
            initContentTree_area(),//初始化左侧区划树
            initContentTree_unit()
        ];
    },
    param: {
        AG_ID_notleaf: false,//点击非叶子节点默认不查询全局变量AG_ID
        AG_NAME_notleaf: false,//点击非叶子节点默认不查询全局变量AG_NAME
        AD_searchable: false//区划树是否可搜索，默认false
    },
    tbar: [//搜索区域
        {
            xtype: 'textfield',
            width: '80%',
            name: 'search_text',
            emptyText: '请输入关键字检索',
            enableKeyEvents: true,
            listeners: {
                keypress: function (self, e) {
                    if (e.getKey() == Ext.EventObject.ENTER) {
                        treeSearch(self);
                    }
                }
            }
        },
        {
            xtype: 'button',
            text: '搜索',
            handler: function (self) {
                treeSearch(self);
            }
        }
    ]
};
/**
 * 初始化左侧树
 * config:{
                items_tree: function () {
                    return [
                        initContentTree_area()//初始化左侧区划树
                    ];
                },
                param:{
                    AG_ID_notleaf;false,//点击非叶子节点默认不查询全局变鲁昂AG_ID
                    AG_NAME_notleaf:false//点击非叶子节点默认不查询全局变鲁昂AG_NAME
                }
            }
 *
 */
function initContentTree(config) {
    Ext.define('treeModel', {
        extend: 'Ext.data.Model',
        fields: [
            {name: 'text'},
            {name: 'code'},
            {name: 'id'},
            {name: 'leaf'}
        ]
    });
    leftTreeConfig = $.extend({}, leftTreeConfig, config);
    //创建左侧panel
    return Ext.create('Ext.panel.Panel', {
        region: 'west',
        layout: 'vbox',
        height: '100%',
        hidden: !!leftTreeConfig && !!leftTreeConfig.hidden,
        itemId: 'treePanel_left',
        flex: 1,
        border: true,
        //bodyStyle: 'border-width:0 0 0 0;',//设置panel边框有无，去掉上方边框
        items: leftTreeConfig.items_tree()
    });
}

/**
 * 初始化左侧树：区划
 */
function initContentTree_area() {
    //加载左侧上方树数据
    var regStore = Ext.create('Ext.data.TreeStore', {
        proxy: {
            type: 'ajax',
            method: 'POST',
            url: '/report/sys-manage/tree/getRegTreeDataNoCache',
            extraParams: leftTreeConfig.areaConfig.params,
            reader: {
                type: 'json'
            }
        },
        root: 'nodelist',
        model: 'treeModel',
        autoLoad: true
    });
    var area_config = {
        itemId: 'tree_area',
        store: regStore,
        width: '100%',
        border: true,
        rootVisible: false,
        listeners: {
            afterrender: function (self) {
                //选中第一条数据
                if (self.getSelection() == null || self.getSelection().length <= 0) {
                    //选中第一条数据
                    var record = self.getStore().getRoot().getChildAt(0);
                    if (record) {
                        self.getSelectionModel().select(record);
                        itemclick(self, record);
                    }
                }
            },
            itemclick: itemclick
        }
    };
    if (leftTreeConfig.param.AD_searchable) {
        area_config.tbar = leftTreeConfig.tbar;
    }
    area_config = $.extend({}, area_config, leftTreeConfig.areaConfig);
    //创建左侧panel
    var area_panel = Ext.create('Ext.tree.Panel', area_config);
    regStore.addListener('load', function (self) {
        var treeNodeCount = 0;
        getTreeNodes(self.root.childNodes,"childNodes",() => {
            treeNodeCount++;
        });
        if (treeNodeCount <= 3) {
            area_panel.setHeight(24 * 4);
        } else if (treeNodeCount > 3 && treeNodeCount <= 8) {
            area_panel.setHeight(24 * 9);
        } else {
            area_panel.setFlex(1);
        }
        //选中第一条数据
        if (area_panel.getSelection() == null || area_panel.getSelection().length <= 0) {
            var record = self.getRoot().getChildAt(0);
            if (record) {
                area_panel.getSelectionModel().select(record);
                itemclick(area_panel, record);
            }
        }
    });
    return area_panel;
    /**
     * 区划树点击事件
     * @param self
     * @param record
     */
    function itemclick(self, record) {
        AD_NAME = record.get('text');
        AD_CODE = record.get('code');
        AD_ID = record.get('id');
        AG_ID = '';
        AG_CODE = '';
        AG_NAME = '';
        //if (record.get('leaf')) { //叶子节点
            if (Ext.ComponentQuery.query('treepanel#tree_unit')[0]) {
                //刷新下方树
                var unit_tree = Ext.ComponentQuery.query('treepanel#tree_unit')[0];
                var unit_store = unit_tree.getStore();
                unit_store.getProxy().extraParams = {
                    AD_CODE: AD_CODE,
                    SHOW_NUM : SHOW_NUM,
        			VIEW_NAME : VIEW_NAME
                };
                unit_store.load();
            }
        /*
        } else {
            if (Ext.ComponentQuery.query('treepanel#tree_unit')[0]) {
                //刷新下方树
                var unit_tree = Ext.ComponentQuery.query('treepanel#tree_unit')[0];
                var unit_store = unit_tree.getStore();
                //获取单位节点，移除其子节点
                var node = unit_store.getRoot();
                node.removeAll();
                node.insertChild(0, {text: "单位", code: "单位", leaf: true});
            }
        }
        */
        if (reloadGrid) {
            reloadGrid();
        }
    }
}
/**
 * 初始化左侧树：单位
 */
function initContentTree_unit() {
    //加载左侧下方树数据
    var unitStore = Ext.create('Ext.data.TreeStore', {
        proxy: {
            type: 'ajax',
            method: 'POST',
            url: '/report/sys-manage/tree/getUnitTreeData',
            reader: {
                type: 'json'
            }
        },
        root: {
            expanded: true,
            text: "ROOT",
            children: [
                {text: "单位", code: "单位", leaf: true}
            ]
        },
        model: 'treeModel'
    });
    //创建左侧panel
    return Ext.create('Ext.tree.Panel', {
        itemId: 'tree_unit',
        store: unitStore,
        width: '100%',
        border: true,
        margin: '0,0,0,40',
        flex: 1,
        rootVisible: false,
        tbar: leftTreeConfig.tbar,
        listeners: {
            itemclick: function (view, record) {
                if (record.get('leaf')) { //叶子节点
                    AG_ID = record.get('id');
                    AG_CODE = record.get('code');
                    AG_NAME = record.get('text');
                } else {//非叶子节点
                    AG_ID = (leftTreeConfig.param.AG_ID_notleaf) ? record.get('id') : '';
                    AG_NAME = (leftTreeConfig.param.AG_NAME_notleaf) ? record.get('text') : '';
                    AG_CODE = record.get('code');
                }
                if (reloadGrid) {
                    reloadGrid();
                }
            }
        }
    });
}
/**
 * 树检索
 * @param self 搜索按钮/检索框
 */
function treeSearch(self) {
    var tree = self.up('treepanel');
    var treeStroe = tree.getStore();
    var btn_search = tree.down('textfield[name="search_text"]');
    var roonodes = tree.getRootNode();//获取主节点
    var textValue = btn_search.getValue();
    if(textValue == null || textValue == 'undefined' || textValue.length == 0){
    	tree.getView().scrollTo(0, 0, true);
    	tree.getSelectionModel().clearSelections();
        return true;
    }
    //如果搜索框内容与上次搜索内容不一致，更新
    if (!btn_search.search_value || btn_search.search_value.toLowerCase() != textValue.toLowerCase()) {
    	tree.getSelectionModel().clearSelections();
        btn_search.search_start = 0;
        btn_search.search_value = textValue;
        if (typeof(btn_search.search_result)=="undefined") {
        	btn_search.search_result = new Array();
        	btn_search.search_resultCount = 0;
    	}
    }else{
    	if(typeof(tree.getSelectionModel().getSelection()[0])!="undefined"){
    		var treeValue = tree.getSelectionModel().getSelection()[0].data.name;
    		if(!treeValue){
    			treeValue  = tree.getSelectionModel().getSelection()[0].data.text;
    		}
    		btn_search.search_result[btn_search.search_resultCount] = treeValue;
    		btn_search.search_resultCount = btn_search.search_resultCount+1;
        }
    }
    if(!!btn_search.search_result && btn_search.search_start >= treeStroe.getCount()) {
    	btn_search.search_result = new Array();
    }
    expandLeafByFinddata(roonodes,tree,textValue,btn_search.search_result,'treePanel',isNaN(textValue),self.isQueryId);  //开始递归
    //循环store，检索搜索内容是否存在
    var start_index = btn_search.search_start;
    var find = false;
    while (true) {
        btn_search.search_start++;
        if (btn_search.search_start >= treeStroe.getCount()) {
            btn_search.search_start = 0;
        }
        var record = treeStroe.getAt(btn_search.search_start);
        var value = record.get('text');
        if(self.isQueryId){
        	value = value + record.get('id');
        }
        if (isNaN(textValue) ? (value.toLowerCase().indexOf(textValue.toLowerCase()) >= 0):
        	value.substring(0,textValue.length)==textValue) {
        	tree.expandPath(record.getPath('id'));
            var scorll_height = btn_search.search_start * (tree.getView().getNodes()[0].clientHeight) > 100 ? btn_search.search_start * (tree.getView().getNodes()[0].clientHeight) - 100 : 0;
            tree.getSelectionModel().select(record);
            tree.getView().scrollTo(0, scorll_height, true);
            find = true;
            break;
        }
        if (start_index == btn_search.search_start) {
            break;
        }
    }
    if (!find) {
        Ext.toast({
            html: '无此数据',
            closable: false,
            align: 't',
            slideInDuration: 400,
            minWidth: 400
        });
    }
}
/**
 * 树遍历
 * @param tree 数据源
 * @param children 子节点标识名
 * @param callback 回调函数，处理遍历逻辑
 */
function getTreeNodes(tree,children,callback) {
    const walk = (tree, depth = 1) => {
        callback(tree, depth);
        if (tree[children]) {
            tree[children].forEach(node => {
                walk(node, depth + 1);
            });
        }
    };
    tree.forEach(item => {
        walk(item);
    });
}
